/**
* @description: 415. 字符串相加
* @author hewei
* @date 2022/8/1 15:46
* @version 1.0
*/

public class AddStrings {

    public String addStrings1(String num1, String num2) {
        int m = num1.length();
        int n = num2.length();
        int p1 = m - 1;
        int p2 = n - 1;
        StringBuilder stringBuilder = new StringBuilder();
        int flag = 0;
        while (p1 >= 0 || p2 >= 0) {
            char c = (char) ((p1 >= 0 ? num1.charAt(p1) : '0') + (p2 >= 0
                    ? num2.charAt(p2) : '0') - '0');
            int res;
            if (c > '9') {
                res = c - '9' + flag;
                flag = 1;
            } else if (c == '9') {
                res = c + flag - '0';
            } else {
                res = c + flag - '0';
                flag = 0;
            }
            stringBuilder.append(res);
            --p1;
            --p2;
        }
        if (flag == 1) stringBuilder.append(1);
        return stringBuilder.reverse().toString();
    }

    public String addStrings(String num1, String num2) {
        StringBuilder ans = new StringBuilder();
        int m = num1.length(), n = num2.length(), p1 = m - 1, p2 = n - 1;
        int add = 0;
        while (p1 >= 0 || p2 >= 0 || add != 0) {
            int temp = (p1 >= 0 ? num1.charAt(p1) - '0' : 0)
                    + (p2 >= 0 ? num2.charAt(p2) - '0' : 0) + add;
            ans.append(temp % 10);
            add = temp / 10;
            --p1;
            --p2;
        }
        return ans.reverse().toString();
    }
}
